<template>
	<div
		id="page__admin-info"
		class="page__section"
		:class="[isAdmin ? 'role-admin' : 'role-user']"
		v-loading="loading"
	>
		<header class="page__header">
			<h2 class="page__title">
				<i class="el-icon-user-solid"></i>
				<span>个人信息</span>
			</h2>
		</header>
		<div class="page__main">
			<el-form
				ref="form"
				:model="form"
				label-width="85px"
				label-suffix="："
			>
				<el-form-item label="用户名">
					<div style="display: flex;flex-direction: row;align-items: center">
						<el-avatar
							:src="form.avatar"
							icon="el-icon-user-solid"
						></el-avatar>
						<el-button
							style="margin-left: 12px"
							size="mini"
							type="plain"
							@click="$bus.$emit('goods-img__edit')"
						>编辑头像
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="用户名">
					<el-input
						v-model="form.username"
						@input="changeUsername"
						@blur="validateUsername"
						size="small"
					>
						<i
							v-if="usernameLoading"
							slot="suffix"
							class="el-input__icon el-icon-loading"></i>
					</el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input
						v-model="form.password"
						size="small"
						show-password
					></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-select
						v-model="form.gender"
						size="small"
					>
						<el-option
							v-for="item in GENDER_LIST"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker
						v-model="form.birthday"
						type="date"
						size="small"
						value-format="yyyy-MM-dd"
					></el-date-picker>
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input
						v-model="form.email"
						size="small"
					></el-input>
				</el-form-item>
				<el-form-item label="手机号码">
					<el-input
						v-model="form.phone"
						size="small"
					></el-input>
				</el-form-item>
				<el-form-item prop="provinceCityArea" label="区域">
					<el-cascader
						v-model="form.provinceCityArea"
						style="width: 220px"
						size="small"
						filterable
						:options="options"
						:props="{ expandTrigger: 'hover' }"
					></el-cascader>
				</el-form-item>
				<el-form-item label="地址">
					<el-input
						v-model="form.address"
						size="small"
					></el-input>
				</el-form-item>
				<el-form-item>
					<template slot="label"></template>
					<el-button
						style="width: 80px"
						size="small"
						type="primary"
						@click="updateUser"
					>保存
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<img-edit title="编辑头像" @submit="updateAvatar"/>
	</div>
</template>

<script>
  /**
   *
   *
   *
   */
  import Validators from "../config/validators";
  import utils from "../utils";
  import * as CONSTANT from '../config/constant'
  import {mapState} from 'vuex'
  import options from "../config/china-division";
  import imgEdit from './goods/img-edit'

  const validator = new Validators()
  let defaultRegisterForm = utils.getDefaultRegisterForm();
  export default {
    name: "info",
    data() {
      return {
        ...CONSTANT,
        options: options,
        form: defaultRegisterForm,
        rules: {
          username: [{required: true, validator: validator.validateUsername, trigger: 'change'}],
          password: [{required: true, validator: validator.validatePassword, trigger: 'change'}],
          gender: [{required: true, validator: validator.validateGender, trigger: 'change'}],
          birthday: [{required: true, validator: validator.validateBirthday, trigger: 'change'}],
          email: [{required: true, validator: validator.validateEmail, trigger: 'change'}],
          phone: [{required: true, validator: validator.validatePhone, trigger: 'change'}],
          provinceCityArea: [{required: true, validator: validator.validateProvinceCityArea, trigger: 'change'}],
          address: [{required: true, validator: validator.validateAddress, trigger: 'change'}]
        },
        loading: false,
        usernameLoading: false,
        usernameError: undefined
      }
    },
    computed: {
      ...mapState([
        'userInfo'
      ]),
      isAdmin() {
        let userInfo = this.userInfo || {}
        return userInfo.role === 1
      }
    },
    watch: {
      'form.provinceCityArea': {
        deep: true,
        immediate: true,
        handler(list) {
          let [province, city, area] = list || []
          this.form.province = province || ''
          this.form.city = city || ''
          this.form.area = area || ''
        }
      },
      userInfo(userInfo) {
        this.form = {
          ...userInfo,
          provinceCityArea: [userInfo.province || '', userInfo.city || '', userInfo.area || '']
        }
      }
    },
    async mounted() {
      validator.context = this
      this.loading = true
      await this.$store.dispatch('getUserInfo')
      this.loading = false
    },
    methods: {
      updateAvatar(data) {
        this.form.avatar = data
      },
      changeUsername() {
        this.usernameError = undefined
      },
      validateUsername() {
        const api = '/user/isUsernameValid'
        let username = this.form.username
        this.$cancel(api)
        this.usernameError = undefined
        if (!username) {
          this.usernameLoading = false
          return false
        }
        this.usernameLoading = true
        this.$axios.post(api, {
          username: this.form.username,
          uid: this.form.id
        }).then(({success, message}) => {
            if (!success) {
              this.usernameError = message
            }
          })
          .catch(thrown => {
            this.$message({
              type: 'error',
              message: thrown.message
            })
          })
          .finally(() => {
            this.usernameLoading = false
          })
      },
      updateUser() {
        this.$refs.form.validate(valid => {
          if (!valid) return
          this.loading = true
          let params = {
            ...this.form
          }
          delete params.provinceCityArea
          this.$axios.post('/user/save', params)
            .then(({success, message}) => {
              if (success) {
                this.$store.commit('updateUserInfo', params)
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
              } else {
                if (/用户名/.test(message)) {
                  this.usernameError = message
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              }
            })
            .catch(thrown => {
              this.$message({
                type: 'error',
                message: thrown.message
              })
            })
            .finally(() => {
              this.loading = false
            })
        })
      }
    },
    components: {
      imgEdit
    }

  }
</script>

<style lang='less'>
	#page__admin-info {
		box-sizing: border-box;

		.el-icon-user-solid {
			color: #409EFF;
		}

		&.role-user {

			.page__main {
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
				border-radius: 4px;
				padding-bottom: 10px;
			}

		}

		.el-form {
			width: 100%;
			max-width: 480px;
		}
	}
</style>
